package com.gufe.service.admin.impl.club;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gufe.entity.PPTQueryParam;
import com.gufe.entity.PrecollectMember;
import com.gufe.mapper.admin.club.ApplyMemberMapper;
import com.gufe.result.PageResult;
import com.gufe.service.admin.club.ApplyMemberService;
import com.gufe.vo.PPTvo.ApplyMemberVO;
import com.gufe.vo.PPTvo.CollegeCountVO;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

@Service
public class ApplyMemberServiceImpl implements ApplyMemberService {

    @Autowired
    private ApplyMemberMapper applyMemberMapper;
    /**
     * 批量同意预征班申请
     * @param ids
     */
    public void agreeApply(List<Integer> ids) {
        applyMemberMapper.agreeApply(ids);
    }

    /**
     * 查询预征班申请成员中各个学院的人数总计
     * @return
     */
    public List<CollegeCountVO> getCollegeCount() {
        return applyMemberMapper.getCollegeCount();
    }


    /**
     * 条件查询预征班申请人员信息
     * @param pptQueryParam
     * @return
     */
    public PageResult<ApplyMemberVO> getApplyMember(PPTQueryParam pptQueryParam) {
        // 将前端传递过来的 男 和 女 转换为其对应的数字 男：1 女：0
        if (Objects.equals(pptQueryParam.getGender(), "男")){
            pptQueryParam.setGender("1");
        } else if (Objects.equals(pptQueryParam.getGender(), "女")) {
            pptQueryParam.setGender("0");
        }

        // 设置分页参数
        PageHelper.startPage(pptQueryParam.getPage(),pptQueryParam.getPageSize());

        // 执行查询
        List<ApplyMemberVO> applymemberVOList = applyMemberMapper.getApplyMembers(pptQueryParam);

        // 解析查询结果并封装
        Page<ApplyMemberVO> p = (Page<ApplyMemberVO>) applymemberVOList;
        return new PageResult<>(p.getTotal(),p.getResult());
    }

    // 根据ID获取申请人员信息
    public PrecollectMember getInfoById(Integer id) {
        PrecollectMember member = applyMemberMapper.getInfoById(id);
        // 处理性别
        if(Objects.equals(member.getGender(), "1"))
            member.setGender("男");
        else if (Objects.equals(member.getGender(), "0")) {
            member.setGender("女");
        }
        return member;
    }

    /**
     * 根据ID导出预征班成员信息
     * @param id
     */
    public XSSFWorkbook exportInfo(Integer id) throws IOException {
        // 读取 Excel 模版
        InputStream templateStream = getClass().getClassLoader().getResourceAsStream("module/贵州财经大学预征班学员申请表Demo.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(templateStream);
        Sheet sheet = workbook.getSheetAt(0); // 选择第一个工作表

        // 获取成员数据
        PrecollectMember member = getInfoById(id);

        // 插入照片
        if (member.getImgUrl() != null && !member.getImgUrl().isEmpty()) {
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                // 创建 HTTP 请求
                HttpGet httpGet = new HttpGet(member.getImgUrl());
                // 执行请求并获取响应
                try (CloseableHttpResponse response = httpClient.execute(httpGet);
                     InputStream inputStream = response.getEntity().getContent()) {
                    // 将图片流读取为字节数组
                    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                    byte[] data = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
                        buffer.write(data, 0, bytesRead);
                    }
                    byte[] imageBytes = buffer.toByteArray();
                    // 判断图片类型
                    int pictureType = Workbook.PICTURE_TYPE_JPEG;
                    if (member.getImgUrl().toLowerCase().endsWith(".png")) {
                        pictureType = Workbook.PICTURE_TYPE_PNG;
                    }
                    // 将图片添加到工作簿
                    int pictureIdx = workbook.addPicture(imageBytes, pictureType);
                    // 创建绘图工具
                    CreationHelper helper = workbook.getCreationHelper();
                    Drawing<?> drawing = sheet.createDrawingPatriarch();
                    // 设置图片位置（示例：Excel中的G3单元格）
                    ClientAnchor anchor = helper.createClientAnchor();
                    anchor.setCol1(6);  // 第7列（G列）
                    anchor.setRow1(3);  // 第4行
                    // 插入图片并调整大小
                    Picture pict = drawing.createPicture(anchor, pictureIdx);
                    // 获取图片原始尺寸（单位：像素）
                    double imageWidth = pict.getImageDimension().getWidth();
                    double imageHeight = pict.getImageDimension().getHeight();
                    // 计算单元格总宽高（像素）
                    float cellWidth = sheet.getColumnWidthInPixels(6); // G列宽（像素）
                    float cellHeight = 0;
                    for (int i = 3; i <= 6; i++) {
                        Row row = sheet.getRow(i);
                        if (row == null) continue;
                        cellHeight += row.getHeightInPoints() * 96 / 72; // 行高转像素
                    }
                    // 计算缩放比例
                    double scale = Math.min(cellWidth / imageWidth, cellHeight / imageHeight);
                    // 计算最终显示尺寸
                    double displayWidth = imageWidth * scale;
                    double displayHeight = imageHeight * scale;
                    // 计算居中偏移（EMU单位）
                    long dx = (long) ((cellWidth - displayWidth) / 2 * 9525);
                    long dy = (long) ((cellHeight - displayHeight) / 2 * 9525);
                    // 添加参数有效性检查
                    if (dx < 0 || dy < 0) {
                        throw new IllegalArgumentException("计算得到负偏移量，检查单元格尺寸是否过小");
                    }
                    // 设置锚点参数
                    anchor.setDx1((int) dx);
                    anchor.setDy1((int) dy);
                    // 调整图片大小
                    pict.resize(scale);
                }
            } catch (IOException e) {
                throw new IOException("图片下载或插入失败: " + e.getMessage());
            }
        }


        // 填充 Excel 数据
        sheet.getRow(2).getCell(1).setCellValue(member.getCollege()); // 学院
        sheet.getRow(2).getCell(5).setCellValue(member.getFormTime().substring(0, 10)); // 填表时间

        sheet.getRow(3).getCell(1).setCellValue(member.getName()); // 姓名

        sheet.getRow(3).getCell(3).setCellValue(Objects.equals(member.getGender(), "1") ?"男":"女"); // 性别
        sheet.getRow(3).getCell(5).setCellValue(member.getBirthDate()); // 出生年月

        sheet.getRow(4).getCell(1).setCellValue(member.getNationality()); // 民族
        sheet.getRow(4).getCell(3).setCellValue(member.getNativePlace()); // 籍贯
        sheet.getRow(4).getCell(5).setCellValue(member.getPoliticalAffiliation()); // 政治面貌

        sheet.getRow(5).getCell(1).setCellValue(member.getCollege()); // 学院
        sheet.getRow(5).getCell(4).setCellValue(member.getClassName()); // 班级

        sheet.getRow(6).getCell(1).setCellValue(member.getStudentId()); // 学号
        sheet.getRow(6).getCell(4).setCellValue(member.getIdCard()); // 身份证号

        sheet.getRow(7).getCell(1).setCellValue(member.getContactNumber()); // 联系电话
        sheet.getRow(7).getCell(4).setCellValue(member.getHomeAddress()); // 家庭地址

        sheet.getRow(8).getCell(1).setCellValue(member.getResume()); // 个人简历

        sheet.getRow(9).getCell(1).setCellValue(member.getHonorsAwarded()); // 表彰

        sheet.getRow(11).getCell(1).setCellValue(member.getCollegeOpinion()); // 学院意见

        sheet.getRow(13).getCell(1).setCellValue(member.getInitialInspection()); // 初检情况

        return workbook; // 返回 Excel 对象
    }

}
